//获取应用实例
const app = getApp()
const WXAPI = require('../../Wxapi/api.js')
Page({
  data: {
    ty: 0, //手指开始触摸时的位置
    idx: 0, //当前视频索引
    num: 0, //当前视频栈的总个数
    scrollTop: 0, //用来隐藏video 标签
    scrollStart: '', //滚动动画
    height: 0, //设备高度,
    cdnRoot: app.globalData.cdnRoot,
    fh: app.globalData.cdnRoot + wx.getStorageSync("activeInfo").rank_logo_first, //第一名徽章
    sh: app.globalData.cdnRoot + wx.getStorageSync("activeInfo").rank_logo_second, //第二名徽章
    th: app.globalData.cdnRoot + wx.getStorageSync("activeInfo").rank_logo_third, //第三名徽章
    
    is_hide: true,
    list: [],
    rank: [],

    obj: '',
    loginInfo: {
      title: '微信授权',
      content: '获得您的公开信息(昵称、头像等)',
      logName: '普瑞眼科',
      logImage: '/images/wx.png',
    },
    is_first: true
  },
  onLoad: function (obj) {
    let that = this;
    that.setData({
      obj: obj
    })
  },
  /**
   * 渲染页面
   */
  onShow: function (){
    let that = this,
        dialogComponent = that.selectComponent('.wxc-dialog'),
        obj = that.data.obj,
        c = that.data.is_first;
    if(c === false){
      WXAPI.getOtherTimes({
        openId: wx.getStorageSync('openId'),
        aid: wx.getStorageSync("activeInfo").id,
        uid: wx.getStorageSync('uid'),
        hid: wx.getStorageSync('activeInfo').h_id
      }).then(function (res) {
        if (res.code === 200) {
          wx.showToast({
            title: '投票次数+1',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: res.errorMsg,
            icon: "none",
            duration: 2000
          })
        }
      })
    }
    // 判断用户状态
    wx.checkSession({
      success() {
        // 已登录
        if (wx.getStorageSync("userInfo")) {
          wx.showShareMenu({
            withShareTicket: true
          })
          let vid = obj.id,
            uid = wx.getStorageSync("uid");
          if (vid === 0 || vid === '' || vid === null) {
            wx.showToast({
              title: '获取失败!',
              icon: 'none',
              duration: 1500,
              success: function () {
                setTimeout(function () {
                  wx.navigateBack()
                }, 1500)
              }
            })
          } else {
            // 获取视频资源
            let result = that.getVideoInfo(vid, uid);
            if (result) {
              wx.getSystemInfo({
                success: function (res) {
                  that.setData({
                    height: res.windowHeight
                  })
                }
              })
            }
          }
        } else {
          dialogComponent && dialogComponent.show();
        }
      },
      fail() {
        dialogComponent && dialogComponent.show();
      }
    })
  },

  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function (res) {
    let that = this
        
    that.setData({
      is_first: false
    })   
    // WXAPI.getOtherTimes({
    //   openId: wx.getStorageSync('openId'),
    //   aid: wx.getStorageSync("activeInfo").id,
    //   uid: wx.getStorageSync('uid')
    // }).then(function (res) {
    //   if (res.code === 200) {
    //     wx.showToast({
    //       title: '投票次数+1',
    //       duration: 5000
    //     })
    //   } else {
    //     wx.showToast({
    //       title: res.errorMsg,
    //       icon: "none",
    //       duration: 5000
    //     })
    //   }
    // })

    return {
      title: "快给 " + that.data.list[that.data.idx].id + "号 " + that.data.list[that.data.idx].name + " #" + that.data.list[that.data.idx].topic + "# 投票吧",
      path: '/pages/index/index?which=video&id=' + that.data.list[that.data.idx].id,
      imageUrl: app.globalData.cdnRoot + wx.getStorageSync("activeInfo").share_logo
    }
    
  },

  /**
   * 开始触摸
   * @param e
   */
  onTouchStart: function (e) {
    let tp = e.changedTouches[0]; //记录手指位置
    this.setData({
      ty: tp.pageY
    })
  },
  /**
   * 手指离开
   * @param e
   */
  onTouchEnd: function (e) {
    let that = this,
      videoInfo = that.data,
      tp = e.changedTouches[0]; //手指结束时位置
    if (tp.pageY - videoInfo.ty < - 100) {  //向下滚动时的处理 -100为触发条件
      if ((videoInfo.idx + 1) < videoInfo.num) {
        that.setData({
          idx: videoInfo.idx + 1
        })
      } else {
        // 获取下一视频
        that.getVideoInfo(videoInfo.list[videoInfo.idx].id, wx.getStorageSync("uid"), 1)
      }
    } else if (tp.pageY - videoInfo.ty > 100 && videoInfo.idx > 0) { //向上滚动的判断，要区分是否将滚到第一个视频，添加不同动画
      // 获取上一视频缓存
      that.setData({
        idx: videoInfo.idx - 1
      })
    } else if (tp.pageY - videoInfo.ty > 100) {
      // 获取上一视频
      that.getVideoInfo(videoInfo.list[videoInfo.idx].id, wx.getStorageSync("uid"), 2)
    }
  },
  getVideoInfo: function (vid, uid, type = null) {
    let that = this,
        list = that.data.list;
    WXAPI.getVideoInfo({
      vid: vid,
      uid: uid,
      type: type
    }).then(function (res) {
      if (res.code === 200) {
        that.setData({
          num: that.data.num + 1
        })
        if (type === 1) {
          list.push(res.data)
          that.setData({
            idx: that.data.idx + 1
          })
        } else if (type === 2) {
          list.unshift(res.data)
          if (that.data.idx > 0) {
            that.setData({
              idx: that.data.idx - 1
            })
          } else {
            that.setData({
              idx: 0
            })
          }

        } else {
          list.push(res.data)
        }
        that.setData({
          list: list
        })
      } else {
        wx.showToast({
          title: '已经到顶了!',
          icon: 'none',
          duration: 1500
        })
      }
    })
  },
  // 投票
  doVote: function(){
    let that = this,
      dialogComponent = that.selectComponent('.wxc-dialog');
    // 判断用户状态
    wx.checkSession({
      success() {
        // 已登录
        if (wx.getStorageSync("userInfo")) {
          // 投票
          WXAPI.checkDoVote({
            vid: that.data.list[that.data.idx].id,
            uid: wx.getStorageSync('uid'),
            openId: wx.getStorageSync('openId'),
            aid: wx.getStorageSync("activeInfo").id,
            hid: wx.getStorageSync("activeInfo").h_id
          }).then(function (res) {
            if (res.code === 200) {
              wx.showToast({
                title: '投票成功',
                duration: 1500
              })
              let change = "list[" + that.data.idx + "].votes",
                  num = "list[" + that.data.idx + "].num";
              that.setData({
                [change]: that.data.list[that.data.idx].votes * 1 + 1,
                [num]: that.data.list[that.data.idx].num * 1 + 1
              })
            } else {
              wx.showToast({
                title: res.errorMsg,
                icon: "none",
                duration: 1500
              })
            }
          })
        } else {
          dialogComponent && dialogComponent.show();
        }
      },
      fail() {
        dialogComponent && dialogComponent.show();
      }
    })
  },
  //打开规则提示
  showRule: function () {
    wx.showLoading({
      title: '正在加载...'
    })

    let that = this;
    // 获取排行
    WXAPI.getRankInfo({
      aid: wx.getStorageSync('activeInfo').id
    }).then(function (res) {
      if (res.code === 200) {
        that.setData({
          rank: res.list,
          isRuleTrue: true
        })
      }
    }).finally(function () {
      wx.hideLoading()
    })
  },//关闭规则提示
  hideRule: function () {
    this.setData({
      isRuleTrue: false
    })
  },
  navback: function(){
    setTimeout(function(){
      wx.navigateBack()
    }, 500)
  },
  onConfirm(e) { // 点击允许
    let that = this,
        dialogComponent = that.selectComponent('.wxc-dialog');
    let userInfo = e.detail.detail.rawData
    if (!userInfo) {
      return false
    } else {
      that.login()
    }
  },
  login: function () {
    let that = this;
    wx.login({
      success: function (res) {
        WXAPI.getUserInfo({
          code: res.code
        }).then(function (res) {
          if (res.code == 200) {
            wx.setStorageSync("uid", res.user_info.id);
            wx.setStorageSync("openId", res.user_info.openId)
            wx.getUserInfo({
              success: function (res) {
                wx.setStorageSync("userInfo", res.userInfo)
              },
              complete: function () {
                let dialogComponent = that.selectComponent('.wxc-dialog');
                dialogComponent && dialogComponent.hide();
                that.onShow()
              }
            })
          } else if (res.code == 201) {
            // 注册用户
            that.registerUser(res.openId)
          }
        })
      }
    })
  },
  // 注册
  registerUser: function (openId) {
    let that = this;
    wx.login({
      success: function (res) {
        let code = res.code; // 微信登录接口返回的 code 参数，下面注册接口需要用到
        wx.getUserInfo({
          success: function (res) {
            let avatarUrl = res.userInfo.avatarUrl,
              nickName = res.userInfo.nickName,
              gender = res.userInfo.gender,
              country = res.userInfo.country,
              province = res.userInfo.province,
              city = res.userInfo.city
            // 下面开始调用注册接口
            WXAPI.register({
              avatarUrl: avatarUrl,
              nickName: nickName,
              openId: openId,
              gender: gender,
              country: country,
              province: province,
              city: city,
            }).then(function (res) {
              that.login()
            })
          }
        })
      }
    })
  }
})